using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GunForEnemy : MonoBehaviour
{
    public float angle;
    public float interval;
    public float range;
    public GameObject bulletPrefab;
    public GameObject father;
    public Transform muzzlePos;
    protected Vector2 mousePos;
    protected Vector2 direction;
    protected float timer;
    protected Animator anim;
    // Start is called before the first frame update
    protected virtual void Start()
    {
        anim = GetComponent<Animator>();
        muzzlePos = transform.Find("Muzzle");
        if (father.GetComponent<FSM>() != null)
        { range = father.GetComponent<FSM>().parameter.area; }
        //if (father.GetComponent<FSM2>() != null)
        //{ range = father.GetComponent<FSM2>().parameter.area; }
    }
    
    // Update is called once per frame
    protected virtual void Update()
    {
        //mousePos = GameObject.FindWithTag("Player").transform.position;
        if (father.GetComponent<FSM>() != null)
            mousePos = father.GetComponent<FSM>().parameter.target.position;
        if (father.GetComponent<FSM2>() != null)
            mousePos = father.GetComponent<FSM2>().parameter.target.position;
        if (mousePos.x < transform.position.x)
        {
            transform.localScale = new Vector3(-1, -1, 1);
        }
        else
        {
            transform.localScale = new Vector3(1, 1, 1);
        }
        direction = (mousePos - new Vector2(transform.position.x, transform.position.y)).normalized;
        transform.right = direction;
        Shoot();
    }
    protected virtual void Shoot()
    {

        if (timer != 0)
        {
            timer -= Time.deltaTime;
            if (timer <= 0)
            {
                timer = 0;
            }
        }
        if (anim.GetCurrentAnimatorClipInfo(0)[0].clip.name == "Shoot" && timer == 0)
        {
            fire();
        }
    }
    protected virtual void fire()
    {
        timer = interval;
        anim.SetTrigger("shoot");
        //GameObject bullet = Instantiate(bulletPrefab,muzzlePos.position,Quaternion.identity);
        GameObject bullet = ObjectPool.Instance.GetObject(bulletPrefab);
        float angel = Random.Range(-angle / 2, angle / 2);
        bullet.transform.position = muzzlePos.position;
        Vector2 _direction = Quaternion.AngleAxis(angel, Vector3.forward) * direction;
        bullet.transform.right = _direction;
        bullet.GetComponent<bullet>().SetSpeed(_direction);       
    }
}
